OC.Share={
   SHARE_TYPE_USER:0,
   SHARE_TYPE_GROUP:1,
   SHARE_TYPE_LINK:3,
   SHARE_TYPE_EMAIL:4,
   itemShares:[],
   statuses:[],
   droppedDown:false,
   loadIcons:function(itemType) {
      // Load all share icons
      $.get(OC.filePath('resumes', 'ajax', 'share.php'), { fetch: 'getItemsSharedStatuses', itemType: itemType }, function(result) {
         if (result && result.status === 'success') {
            $.each(result.data, function(item, data) {
               OC.Share.statuses['s'+item] = data;
               var hasLink = data['link'];
               // Links override shared in terms of icon display
               if (hasLink) {
                  var image = OC.imagePath('core', 'actions/public');
               } else {
                  var image = OC.imagePath('core', 'actions/shared');
               }
               if (itemType != 'file' && itemType != 'folder') {
                  $('a.share[data-item="'+item+'"]').addClass('shared');
               } else {
                  var file = $('tr').filterAttr('data-id', item);
                  if (file.length > 0) {
                     var action = $(file).find('.fileactions .action').filterAttr('data-action', 'Share');
                     var img = action.find('img').attr('src', image);
                     action.addClass('permanent');
                     action.html(' '+t('core', 'Shared')).prepend(img);
                  } else {
                     var dir = $('#dir').val();
                     if (dir.length > 1) {
                        var last = '';
                        var path = dir;
                        // Search for possible parent folders that are shared
                        while (path != last) {
                           if (path == data['path']) {
                              var actions = $('.fileactions .action').filterAttr('data-action', 'Share');
                              $.each(actions, function(index, action) {
                                 var img = $(action).find('img');
                                 if (img.attr('src') != OC.imagePath('core', 'actions/public')) {
                                    img.attr('src', image);
                                    $(action).addClass('permanent');
                                    $(action).html(' '+t('core', 'Shared')).prepend(img);
                                 }
                              });
                           }
                           last = path;
                           path = OC.Share.dirname(path);
                        }
                     }
                  }
               }
            });
         }
      });
   },
   updateIcon:function(itemType, itemSource) {
      var shares = false;
      var link = false;
      var image = OC.imagePath('core', 'actions/share');
      $.each(OC.Share.itemShares, function(index) {
         if (OC.Share.itemShares[index]) {
            if (index == OC.Share.SHARE_TYPE_LINK) {
               if (OC.Share.itemShares[index].length > 0) {
                  shares = true;
                  image = OC.imagePath('core', 'actions/public');
                  link = true;
                  return false;
               }
            } else if (OC.Share.itemShares[index].length > 0) {
               shares = true;
               image = OC.imagePath('core', 'actions/shared');
               return false;
            }
         }
      });
      if (itemType != 'file' && itemType != 'folder') {

         var shared = $('a.share[data-item="'+itemSource+'"]').hasClass('shared'); 
         !shares && shared ? $('a.share[data-item="'+itemSource+'"]').removeClass('shared'):
                             $('a.share[data-item="'+itemSource+'"]').addClass('shared'); 
      } else {
         var file = $('tr').filterAttr('data-id', String(itemSource));
         if (file.length > 0) {
            var action = $(file).find('.fileactions .action').filterAttr('data-action', 'Share');
            var img = action.find('img').attr('src', image);
            if (shares) {
               action.addClass('permanent');
               action.html(' '+ escapeHTML(t('core', 'Shared'))).prepend(img);
            } else {
               action.removeClass('permanent');
               action.html(' '+ escapeHTML(t('core', 'Share'))).prepend(img);
            }
         }
      }
      if (shares) {
         if(typeof(OC.Share.statuses['s'+itemSource]) === 'undefined')
            OC.Share.statuses['s'+itemSource] = {};
         OC.Share.statuses['s'+itemSource]['link'] = link;
      } else {
         if(typeof(OC.Share.statuses['s'+itemSource]) !== 'undefined')
            delete OC.Share.statuses['s'+itemSource];
      }
   },
   loadItem:function(itemType, itemSource) {
      $.ajaxSetup({ cache: false });
      var data = '';
      var checkReshare = true;
      if (typeof OC.Share.statuses['s'+itemSource] === 'undefined') {
         // NOTE: Check does not always work and misses some shares, fix later
         checkShares = true;
      } else {
         checkShares = true;
      }
      $.ajax({type: 'GET', url: OC.filePath('resumes', 'ajax', 'share.php'), data: { fetch: 'getItem', itemType: itemType, itemSource: itemSource, checkReshare: checkReshare, checkShares: checkShares }, async: false, success: function(result) {
         if (result && result.status === 'success') {
            data = result.data;
         } else {
            data = false;
         }
      }});
      return data;
   },  
   loadPositionEmail:function(itemType, itemSource) {
      $.ajaxSetup({ cache: false });
      var email = '';
      $.ajax({type: 'GET', url: OC.filePath('resumes', 'ajax', 'share.php'), data: { fetch: 'getpositionemail', itemType: itemType, itemSource: itemSource }, async: false, success: function(result) {
         if (result && result.status === 'success') {
        	 email = result.data;
         } else {
        	 email = false;
         }
      }});
      return email;
   },
   share:function(itemType, itemSource, shareType, shareWith, permissions, expiration, shareWords, setting, okcb, failcb) {
      $.post(OC.filePath('resumes', 'ajax', 'share.php'), 
         { 
            action: 'share', 
            itemType: itemType, 
            itemSource: itemSource, 
            shareType: shareType, 
            shareWith: shareWith, 
            permissions: permissions,
            expiration:expiration,
            shareWords: shareWords,
            setting: setting 
         }, 
         function(result) {
            if (!isLoggedIn(result)) {
               if($.isFunction(failcb)) {
                  failcb('您需要登陆');
               }
               
               window.location = redirect_url;
               return;
            }
            
            if(!$.isPlainObject(result)) {
               result = $.parseJSON(result);
            }
            
            if (result && result.status === 'success') {
               if($.isFunction(okcb)) {
                  okcb(result.data);
               }
            } else if($.isFunction(failcb)) {
               failcb(result.data.message);
            }
         })
   },
   unshare:function(itemType, itemSource, shareType, shareWith, okcb, failcb) {
      $.post(OC.filePath('resumes', 'ajax', 'share.php'), { action: 'unshare', itemType: itemType, itemSource: itemSource, shareType: shareType, shareWith: shareWith }, function(result) {
         if (!isLoggedIn(result)) {
            if($.isFunction(failcb)) {
               failcb('您需要登陆');
            }
            
            window.location = redirect_url;
            return;
         }
         
         if(!$.isPlainObject(result)) {
            result = $.parseJSON(result);
         }
         
         if (result && result.status === 'success') {
            if ($.isFunction(okcb)) {
               okcb();
            }
         } else if($.isFunction(failcb)) {
            failcb();
         }
      });
   },
   setPermissions:function(itemType, itemSource, shareType, shareWith, permissions, okcb, failcb) {
      $.post(OC.filePath('resumes', 'ajax', 'share.php'), { action: 'setPermissions', itemType: itemType, itemSource: itemSource, shareType: shareType, shareWith: shareWith, permissions: permissions }, function(result) {
         if (result && result.status === 'success') {
            if ($.isFunction(okcb)) {
               okcb();
            }
         } else if($.isFunction(failcb)) {
            failcb();
         }
      });
   },
   showDropDown:function(itemType, itemSource, appendTo, link, possiblePermissions) {
	   var data = OC.Share.loadItem(itemType, itemSource);
	   
	      var html = '<div id="shareresumedialog" class="hr_resumes_match popup" data-item-type="'+itemType+'" data-item-source="'+itemSource+'" style="position:absolute; text-align:left; z-index:10; display:none;">';
	      //var html = '<div id="sharedialog" class="drop" data-item-type="'+itemType+'" data-item-source="'+itemSource+'">';
	      if (data !== false && data.reshare !== false && data.reshare.uid_owner !== undefined) {
	         if (data.reshare.share_type == OC.Share.SHARE_TYPE_GROUP) {
	            html += '<label class="reshare">'+t('core', 'Shared with you and the group {group} by {owner}', {group: data.reshare.share_with, owner: "<b>"+data.reshare.displayname_owner+"</b>"})+'</label>';
	         } else {
	            html += '<label class="reshare">'+t('core', 'Shared with you by {owner}', {owner: "<b>"+data.reshare.displayname_owner+"</b>"})+'</label>';
	         }
	      }
	      if (possiblePermissions & OC.PERMISSION_SHARE) {
	    	  html += '<div class="hr_resumes_matchinner">';
	          html += '<div class="hr_top5match" style="width:410px;">';
	          html += '<div class="hr_top5uppoint" style="left:19px;"></div>';
	          html += '<div class="closediv resumeshare"></div>';
	          html += '<div class="sharedialogbox medium">';
	          html += '<p><b>分享简历</b>&nbsp;&nbsp;<span class="smalltexttip">多个地址用英文逗号分隔</span></p>';
	          html += '<div class="sharedialog_inner"><span>分享给：</span><input id="shareWith" data-share-permission="'+(OC.PERMISSION_READ|OC.PERMISSION_SHARE)+'" data-possible-permission="'+possiblePermissions+'" type="text" class="" placeholder="请输入要分享的Email地址" value=""/></div>'; 
	          html += '<div class="sharedialog_inner clearfix" id="sharedialog_inner"><span class="pull-left">已分享：</span>';
	          html += '<ul id="shareWithList">';
	          html += '</ul>';
	          html += '<ul id="sharedemailList">';
	          html += '</ul>';
	          html += '</div>';
	          html += '<div class="sharedialog_inner"><span>分享语：</span><textarea id="sharewords">这份简历不错，看看吧</textarea></div>';
	          html += '<div class="sharedialog_inner lastbtnbox">';
	          html += '<span class="error server" style="padding-top:0px; margin-right:5px; display:inline-block; width:310px; text-align:left;"></span>';
	          html += '<input class="ppp_bluebtn" id="savesharebtn" type="submit" value="分享"/>';
	          html += '<a id="cancelbtn" href="javascript:;">取消</a>';
	          html += '</div>';
	          html += '</div>';
	          html += '</div>';
	          html += '</div>';
	          html += '</div>';
	        /*html += '</ul>';
	          html += '<div class="shareWith">';
	          html += '<div>'; 
	          html += '<input id="shareWith" type="text" data-share-permission="'+OC.PERMISSION_READ+'" data-possible-permission="'+possiblePermissions+'" placeholder="分享给邮箱" />';

	          html += '<div class="dropdown">'+
	                '<a class="permission-toggle dropdown-toggle" data-toggle="dropdown" href="#"><span>可以看</span><b class="caret"></b></a>'+
	                '<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu">' +
	                '<li><a tabindex="-1" data-permission="'+OC.PERMISSION_READ+'" href="#">可以看</a></li>'+
	                //'<li><a tabindex="-1" data-permission="'+OC.PERMISSION_UPDATE+'" href="#">可点评(含以上权限)</a></li>'+
	                '<li><a tabindex="-1" data-permission="'+OC.PERMISSION_SHARE+'" href="#">可分享(含以上权限)</a></li>'+
	                (possiblePermissions & OC.PERMISSION_DELETE ? 
	                   '<li><a tabindex="-1" data-permission="'+OC.PERMISSION_DELETE+'" href="#">可以删(含以上权限)</a></li>' : 
	                   '') + 
	                '</ul></div>';
	          html  += '</div>'; 
	          html += '<button id="savesharebtn" class="btn btn-info">保存并分享</button>'; 
	          html += '&nbsp;&nbsp;<button id="cancelbtn" class="btn btn-link">取消</button>'; 
	          html += '<span class="error server"></span>'; 
	          html += '</div>'; 
               */
	         $(html).appendTo(appendTo).find(".permission-toggle").dropdown();
	         if($.isFunction($.fn.placeholder)){
	            $("#shareresumedialog #shareWith").placeholder();
	         }

         // Reset item shares
         OC.Share.itemShares = [];
         if (data.shares) {
            var shareExpiration = ''; 
            $.each(data.shares, function(index, share) {
               if (share.share_type == OC.Share.SHARE_TYPE_LINK) {
                  if(!share.share_with) {
                     OC.Share.showLink(itemType, share.token, share.share_with, itemSource);
                  } else {
                     OC.Share.addShareWith(share.share_type, share.share_with, share.share_with_displayname,  share.permissions, possiblePermissions, false);
                  }
               } else {
                  if (share.collection) {
                     OC.Share.addShareWith(share.share_type, share.share_with, share.share_with_displayname, share.permissions, possiblePermissions, share.collection);
                  } else {
                     OC.Share.addShareWith(share.share_type, share.share_with, share.share_with_displayname,  share.permissions, possiblePermissions, false);
                  }
               }
               if (share.expiration != null) {
                  shareExpiration = share.expiration; 
               }
            });
            if(shareExpiration.length <= 0)
               OC.Share.showExpirationDate('');
            else 
               OC.Share.showExpirationDate(shareExpiration);
         }
         else {
            OC.Share.showExpirationDate('');
            // get share link. create it if doens't exit 
            OC.Share.share(itemType, itemSource, OC.Share.SHARE_TYPE_LINK, '', OC.PERMISSION_READ, '', '', 1,  function(data) {
               OC.Share.showLink(itemType, data.token, null, itemSource);
            });
         }

       /*  $('#shareresumedialog #shareWith').autocomplete({
            minLength: 1, 
            messages: {
               noResults:'',
               results:function(){}
            },           
            source: function(search, response) {
               $.get(OC.filePath('resumes', 'ajax', 'share.php'), 
                  {fetch: 'getShareWith', search: search.term, itemShares: OC.Share.itemShares }, 
                  function(result) {
                     $('#shareresumedialog #shareWith').data('share-with', '').data('share-type', '');
                     if (result.status == 'success' && result.data.length > 0) {
                        response(result.data);
                        /* automatically fill in shareWith and shareType */
                /*        $.each(result.data, function(k, o) {
                           if(o.value.shareWith == $.trim($('#shareresumedialog #shareWith').val()) || 
                              o.label == $.trim($('#shareresumedialog #shareWith').val())) {
                              $('#shareresumedialog #shareWith').data('share-with', o.value.shareWith).data('share-type', o.value.shareType);
                              return false;
                           }
                        })
                     } else {
                        if(validateEmail(search.term)) {
                           $('#shareresumedialog #shareWith').data('share-with', search.term).data('share-type', OC.Share.SHARE_TYPE_EMAIL);
                           response([{label: '通过Email分享: '+search.term, value: {shareType: OC.Share.SHARE_TYPE_EMAIL, shareWith: search.term}}]);
                        } //else {
                          //response(['未找到子帐号和分组']);
                        //}
                     }
                  });
            },
            focus: function(event, focused) {
               event.preventDefault();
            },
            select: function(event, selected) {
               if(!$.isPlainObject(selected.item.value))
                  return false; 
               event.stopPropagation();
               var itemType = $('#shareresumedialog').data('item-type');
               var itemSource = $('#shareresumedialog').data('item-source');
               var shareType = selected.item.value.shareType;
               var shareWith = selected.item.value.shareWith;
               $(this).val(selected.item.label.replace('通过Email分享: ', '')).data('share-with', shareWith).data('share-type', shareType);
               $('#shareresumedialog .error.server').html('');
               return false; 
            }
         });*/
      }else if (possiblePermissions == OC.PERMISSION_READ) {
         html += '<input id="shareWith" type="text" placeholder="'+t('core', 'Sharing is not allowed')+'" disabled="disabled"/>';
         html += '</div>';
         $(html).appendTo(appendTo);
      } else {
         html += '<input id="shareWith" type="text" placeholder="'+t('core', 'Resharing is not allowed')+'" disabled="disabled"/>';
         html += '</div>';
         $(html).appendTo(appendTo);
      }
      $('#shareresumedialog').fadeIn('fast', function() {
         OC.Share.droppedDown = true;
      });
      $('#shareresumedialog #shareWith').focus();
      if($('#shareresumedialog #shareWithList').children('li').length <= 0){
         var email = OC.Share.loadPositionEmail(itemType, itemSource);
         var emails = email.emails;
         if(emails && emails.length >0){
            $("#shareresumedialog #sharedialog_inner span").text("常用邮箱：");
            $.each(emails,function(index,b){
               OC.Share.addShareWith('resumes', b.share_with, b.share_with, 1, 31,false,true);
            })
         }else{
            $("#shareresumedialog #sharedialog_inner").hide();
         };
      };
   },
   hideDropDown:function(callback) {
      $('#shareresumedialog').fadeOut('fast', function() {
         OC.Share.droppedDown = false;
         $('#shareresumedialog').remove();
         if (typeof FileActions !== 'undefined' || typeof ResumeActions !== 'undefined') {
            $('tr').removeClass('mouseOver');
         }
         if (callback) {
            callback.call();
         }
      });
   },
   addShareWith:function(shareType, shareWith, shareWithDisplayName, permissions, possiblePermissions, collection, source) {
      if (!OC.Share.itemShares[shareType]) {
         OC.Share.itemShares[shareType] = [];
      }
      OC.Share.itemShares[shareType].push(shareWith);
      if (collection) {
         if (collection.item_type == 'file' || collection.item_type == 'folder') {
            var item = collection.path;
         } else {
            var item = collection.item_source;
         }
         var collectionList = $('#shareresumedialog #shareWithList li').filterAttr('data-collection', item);
         if (collectionList.length > 0) {
            $(collectionList).append(', '+shareWith);
         } else {
            var html = '<li style="clear: both;" data-collection="'+item+'">'+t('core', 'Shared in {item} with {user}', {'item': item, user: shareWithDisplayName})+'</li>';
            $('#shareresumedialog #shareWithList').prepend(html);
         }
      } else {
         var showPermissionText = "可以看"; 
         if (permissions & OC.PERMISSION_DELETE) {
            showPermissionText = "可以删"; 
         }
         else if (permissions & OC.PERMISSION_SHARE) {
            showPermissionText = "可分享"; 
         }
         //else if (permissions & OC.PERMISSION_UPDATE) {
         //   showPermissionText = "可点评"; 
         //}

         var html = '<li class="clearfix" style="clear: both;" data-share-permission="'+permissions+'" data-share-type="'+escapeHTML(shareType)+'" data-share-with="'+escapeHTML(shareWith)+'" title="' + escapeHTML(shareWith) + '">';
         var stclass = 'subaccount'; 
         if(shareType == OC.Share.SHARE_TYPE_GROUP) {
            stclass = 'group' 
         }

         html += '<a href="javascript:;" class="pull-left displayname '+stclass+'">'+truncate(escapeHTML(shareWithDisplayName), 28, true) + '</a>';
         if(!source)
            html += '<a href="javascript:;" class="unshare pull-right"><i></i> 撤销分享</a>';

      /* html += '<div class="dropdown">'+
               '<a class="permission-toggle dropdown-toggle" data-toggle="dropdown" href="#"><span>'+showPermissionText+'</span><b class="caret"></b></a>'+
               '<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu">' + 
               '<li><a tabindex="-1" data-permission="'+OC.PERMISSION_READ+'" href="#">可以看</a></li>'+
               //'<li><a tabindex="-1" data-permission="'+OC.PERMISSION_UPDATE+'" href="#">可点评(含以上权限)</a></li>'+
               '<li><a tabindex="-1" data-permission="'+OC.PERMISSION_SHARE+'" href="#">可分享(含以上权限)</a></li>'+
               (possiblePermissions & OC.PERMISSION_DELETE ? 
                  '<li><a tabindex="-1" data-permission="'+OC.PERMISSION_DELETE+'" href="#">可以删(含以上权限)</a></li>' : 
                  '') + 
               '</ul></div>'; */

         html += '</li>';
         if(!source)
            $(html).appendTo('#shareresumedialog #shareWithList').find(".permission-toggle").dropdown();
         else
            $(html).appendTo('#shareresumedialog #sharedemailList').find(".permission-toggle").dropdown();
      }
      $("#shareresumedialog #sharedialog_inner").show();
      $('#shareresumedialog #shareWithTitle').show();
   },
   showLink:function(itemType, token, password, itemSource) {
      //TODO add path param when showing a link to file in a subfolder of a public link share
      var link = parent.location.protocol+'//'+location.host+OC.linkTo('', 'public.php')+'?service='+itemType+'&t='+token;
      $('#shareresumedialog #linkText').val(link);
   },
   dirname:function(path) {
      return path.replace(/\\/g,'/').replace(/\/[^\/]*$/, '');
   },
   setExpirationDate: function(date, callback) {
      var itemType = $('#sharedialog').data('item-type');
      var itemSource = $('#sharedialog').data('item-source');
      $.post(OC.filePath('resumes', 'ajax', 'share.php'), 
         { action: 'setExpirationDate', itemType: itemType, itemSource: itemSource, date: date }, 
         function(result) {
            if($.isFunction(callback)) callback(date);
         }
      );
   },
   showExpirationDate:function(date) {
      if(date.length <=0) {
         $('#sharedialog #expirationDate').val('');
         $('#sharedialog #resetExpDate').hide();
         $('#sharedialog #expirationDate').next().html("加有效期");
      }
      else {
         $('#sharedialog #expirationDate').val(date);
         $('#sharedialog #resetExpDate').show();
      }

      var buttonText = date.length <= 0 ? "加有效期" : "有效期至: " + $.trim(date.replace('00:00:00', ''));

      if(!$.isFunction($.fn.datepicker))
         return; 

      $('#sharedialog #expirationDate').datepicker({
         showOn: "button", 
         buttonText: buttonText,
         dateFormat : 'yy-mm-dd',
         minDate: new Date(),
         onSelect: function(input, instance) {
            OC.Share.setExpirationDate(input, function() {
               $('#sharedialog #expirationDate').next().html("有效期至: " + input);
               $('#sharedialog #resetExpDate').show();
               $('#sharedialog .shareWith #cancelbtn').removeClass('btn-link').addClass('success').html('完成');
            })
         }
      });
      $('#sharedialog #expirationDate').next().addClass('btn btn-link pull-right medium');
   }
}
$(document).ready(function() {
   $(this).click(function(event) {
     var target = $(event.target);
      var isMatched = !target.is('.drop, .ui-datepicker-next, .ui-datepicker-prev, .ui-icon') 
         && !target.closest('#ui-datepicker-div').length;
      if (OC.Share.droppedDown && isMatched && $('#shareresumedialog').has(event.target).length === 0) {
         OC.Share.hideDropDown();
      }
   });

   $(document).on('click', '#sharedialog #settings .dropdown-menu li a', function() {
      var settings = $(this).closest('.dropdown').parent();
      if(settings.attr('data-share-setting') == $(this).data('setting')) {
         return false;
      }

      settings.attr('data-share-setting', $(this).data('setting'));
      $(this).closest('ul').prev().find('span').text($(this).html());
      var itemType = $('#sharedialog').data('item-type');
      var itemSource = $('#sharedialog').data('item-source');
      $.post(OC.filePath('resumes', 'ajax', 'share.php'), { action: 'setSetting', itemType: itemType, itemSource: itemSource, setting: $(this).data('setting')},
         function(result) {
            $('#sharedialog .shareWith #cancelbtn').removeClass('btn-link').addClass('success').html('完成');
         }
      );

      return false;
   });

   $(document).on('click', '#sharedialog #shareWithList .dropdown-menu li a', function() {
      var li = $(this).closest('ul').closest('li'); 
      if(li.attr('data-share-permission') == $(this).data('permission')) {
         return false; 
      }

      li.attr('data-share-permission', $(this).data('permission'));
      $(this).closest('ul').prev().find('span').text($(this).html().replace(/\(.*\)$/, ''));

      OC.Share.setPermissions($('#sharedialog').data('item-type'),
         $('#sharedialog').data('item-source'),
         li.data('share-type'),
         li.data('share-with'),
         $(this).data('permission'),
         function() {
            $('#sharedialog .shareWith #cancelbtn').removeClass('btn-link').addClass('success').html('完成');
         }, 
         function() {
            showMessagePanel('修改分享权限失败！', li, true);
         });

      return false; 
   });

   $(document).on('click', '#sharedialog .shareWith .dropdown-menu li a', function() {
      var input = $('#sharedialog #shareWith');
      if(input.attr('data-share-permission') == $(this).data('permission')) {
         return false;
      }

      $(this).closest('ul').prev().find('span').text($(this).html().replace(/\(.*\)$/, ''));
      input.attr('data-share-permission', $(this).data('permission'));
      return false; 
   });

   $(document).on('click', '#shareresumedialog #cancelbtn', function() {
      OC.Share.hideDropDown();
      return false; 
   });

   $(document).on('keydown', '#shareresumedialog #shareWith', function(event) {
      if(event.keyCode == 13) {
         $('#shareresumedialog #savesharebtn').trigger('click');
         return false;
      }

      return true; 
   });
   

   
   $(document).on('click', '#shareresumedialog #savesharebtn', function() {
     
      var itemType = $('#shareresumedialog').data('item-type');
      var itemSource = $('#shareresumedialog').data('item-source');
      var permission = $('#shareresumedialog #shareWith').attr('data-share-permission');
      var shareWith = $('#shareresumedialog #shareWith').val();
      //here is email
      var shareType = OC.Share.SHARE_TYPE_EMAIL;
      var shareWithDisplayName = $('#shareresumedialog #shareWith').val(); 
      var expirationDate = $('#shareresumedialog #expirationDate').val();
      //1:不需要登录，0:需要登录
      // var shareSetting = $('#shareresumedialog #settings').attr('data-share-setting');
      var shareSetting = 1;
      var possiblePermissions = $('#shareresumedialog #shareWith').data('possible-permission');
      var shareWords = $('#shareresumedialog #sharewords').val();  
      $('#shareresumedialog .error.server').html('');

      

      //if(shareType == OC.Share.SHARE_TYPE_EMAIL) {
      shareWith=$.trim(shareWith.replace(/；|，|;/g, ','));
      
      if(shareWith.length <= 0) {
         $('#shareresumedialog .error.server').html('请填写正确的邮箱后再分享');
         $("#savesharebtn").prop('disabled',false);
         return false;
      }
      $("#savesharebtn").prop('disabled',true);
      
      var arremail=shareWith.replace(/\s+/g, "");
      arremail=arremail.split(",");
      for(var i=0;i <arremail.length;i++){
         if(arremail[i].length>0){
            if(!validateEmail(arremail[i])){
               $('#shareresumedialog .error.server').html('请填写正确的邮箱后再分享:'+arremail[i]);
               $("#savesharebtn").prop('disabled',false);
               return false;
            }
         } 	 
      }
      //}

      //if(!shareWith || shareWith.length <=0 || shareType ==null || shareType.length <= 0 ) {
      //   $('#sharedialog .shareWith .error.server').html('不合法的子帐号或分组');
      //   return false; 
      //}

      // make sure autocomplete is closed 
      //$('#shareresumedialog #shareWith').autocomplete('close');
      $("#shareresumedialog #sharedialog_inner span").text("已分享：");
      OC.Share.share(itemType, itemSource, shareType, shareWith, permission, expirationDate,shareWords, shareSetting, function(data) {
         for(var i=0;i<data.sharelist.length;i++){
            if(data.sharelist[i].length>0){
               OC.Share.addShareWith(shareType, data.sharelist[i], data.sharelist[i], permission,possiblePermissions);   
            }
         }          	    
         OC.Share.updateIcon(itemType, itemSource);
         $('#shareresumedialog #sharedemailList').hide();
         $('#shareresumedialog #shareWith').val('');
         $('#shareresumedialog #sharewords').val('');
         $("#savesharebtn").prop('disabled',false);
         $('#shareresumedialog #cancelbtn').addClass('success').html('完成');
      }, function(errmsg) {
         $("#savesharebtn").prop('disabled',false);
         $('#shareresumedialog .error.server').html(errmsg);
      });

      return false; 
   });

   $(document).on('click', '#shareresumedialog .unshare', function() {
      var li = $(this).parent();
      var itemType = $('#shareresumedialog').data('item-type');
      var itemSource = $('#shareresumedialog').data('item-source');
      var shareType = $(li).data('share-type');
      var shareWith = $(li).data('share-with');
      OC.Share.unshare(itemType, itemSource, shareType, shareWith, function() {
         $(li).remove();
         var index = OC.Share.itemShares[shareType].indexOf(shareWith);
         OC.Share.itemShares[shareType].splice(index, 1);
         OC.Share.updateIcon(itemType, itemSource);

         $('#shareresumedialog #cancelbtn').addClass('success').html('完成');
         // hide the title if no sharing 
         if($('#shareresumedialog #shareWithList').children('li').length <= 0) {
            $('#shareresumedialog #shareWithTitle').hide();
            $("#shareresumedialog #sharedialog_inner").hide();
         }
      }, function(errmsg) {
         if(!errmsg) {
            errmsg = '取消分享失败！';
         }
         showMessagePanel(errmsg, li, true);
      });
   });

  
   
   
   $(document).on('keydown', '#shareresumedialog', function(event) {
      if(event.keyCode == 27) {
         OC.Share.hideDropDown();
         return false; 
      }
   });

   $(document).on('click', '#sharedialog #resetExpDate', function() {
      OC.Share.setExpirationDate('', function(date) {
         OC.Share.showExpirationDate(date);
         $('#sharedialog .shareWith #cancelbtn').removeClass('btn-link').addClass('success').html('完成');
      });
   });

   $(document).on('click', '#shareresumedialog .closediv', function() {
      $('#shareresumedialog #cancelbtn').trigger('click');
   })
      
   $(document).on('click', '#shareresumedialog #sharedemailList .displayname', function() {
      var li = $(this).parent();
      var remembershare = $(li).data('share-with');
      var shareWith = $('#shareresumedialog #shareWith');
      if($.trim(shareWith.val()).length <= 0)
         shareWith.val(remembershare);
      else
         shareWith.val(shareWith.val()+','+remembershare);
   })

   $(document).on('click', '#shareresumedialog #shareWithList .displayname', function() {
      var li = $(this).parent();
      var remembershare = $(li).data('share-with');
      var shareWith = $('#shareresumedialog #shareWith');
      if($.trim(shareWith.val()).length <= 0)
         shareWith.val(remembershare);
      else
         shareWith.val(shareWith.val()+','+remembershare);
   })
});
